<template>
  <div>
    <el-form ref="form" label-width="80px" :model="spu">
      <el-form-item label="Spu名称">
        <el-input placeholder="请输入Spu名称" v-model="spu.spuName"></el-input>
      </el-form-item>
      <el-form-item label="品牌">
        <el-select v-model="spu.tmId" placeholder="请选择品牌">
          <el-option
            :label="tm.tmName"
            :value="tm.id"
            v-for="(tm, index) in tmList"
            :key="tm.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="Spu描述">
        <el-input
          type="textarea"
          v-model="spu.description"
          placeholder="描述"
          rows="4"
        ></el-input>
      </el-form-item>
      <el-form-item label="Spu图片">
        <!-- 上传图片：action图片上传的地址  list-type: 文件列表的类型 
            file-list：照片墙需要展示的数据【数组：数组里面的元素务必要有name、url属性】
            on-preview：图片预览功能
            on-remove:删除图片的时候会触发
        -->
        <el-upload
          action="/dev-api/admin/product/fileUpload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handleAdd"
          :file-list="spuImgList"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-select :placeholder="`还有${unselectsaleAttr.length}未选择`" v-model="attrIdAndAttrName">
          <el-option
            :label="sale.name"
            :value="`${sale.id}:${sale.name}`"
            v-for="(sale, index) in unselectsaleAttr"
            :key="sale.id"
          ></el-option>
        </el-select>
        <el-button 
          type="primary" 
          icon="el-icon-plus" 
          style="margin-left: 10px" 
          :disabled="!attrIdAndAttrName"
          @click="addSaleAttrs">添加销售属性
        </el-button>
      </el-form-item>
      <el-form-item label-width="80px">
        <el-table style="width: 100%" border :data="spu.spuSaleAttrList">
          <el-table-column
            type="index"
            label="序号"
            width="80"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="saleAttrName"
            label="属性名"
            width="120"
          ></el-table-column>
          <el-table-column prop="prop" label="属性值名称列表" width="width">
            <template slot-scope="scope">
              <el-tag
                :key="tag.id"
                v-for="(tag, index) in scope.row.spuSaleAttrValueList"
                closable
                :disable-transitions="false"
                @close="handleClose(scope.row, index)"
              >
                {{ tag.saleAttrValueName }}
              </el-tag>
              <el-input
                class="input-new-tag"
                v-if="scope.row.inputVisible"
                v-model="scope.row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(scope.row)"
                @blur="handleInputConfirm(scope.row)"
              >
              </el-input>
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="showInput(scope.row)"
                >添加</el-button
              >
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="120">
            <template slot-scope="scope">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="spu.spuSaleAttrList.splice(scope.$index, 1)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="saveOrUpdateSpuInfo">保存</el-button>
        <el-button @click="cancle">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "SpuForm",
  data() {
    return {
      dialogImageUrl: "",
      dialogVisible: false,
      spu: {
        category3Id: "",
        description: "",
        tmId: "",
        spuName: "",
        spuImageList: [
          {
            id: 0,
            imgName: "",
            imgUrl: "",
            spuId: 0,
          },
        ],
        spuSaleAttrList: [
          //   {
          //     baseSaleAttrId: 0,
          //     id: 0,
          //     saleAttrName: "",
          //     spuId: 0,
          //     spuSaleAttrValueList: [
          //       {
          //         baseSaleAttrId: 0,
          //         id: 0,
          //         isChecked: "",
          //         saleAttrName: "",
          //         saleAttrValueName: "",
          //         spuId: 0,
          //       },
          //     ],
          //   },
        ],
      },
      tmList: [],
      spuImgList: [],
      saleAttrList: [],
      attrIdAndAttrName:'',
    };
  },
  computed: {
    unselectsaleAttr(){
      // every,过滤数组，返回一个新数组
      let result = this.saleAttrList.filter(item => {
        // every返回true或false
        return this.spu.spuSaleAttrList.every(sale => {
          return item.name != sale.saleAttrName
        })
      })
      return result
    }
  },
  methods: {
    // 删除图片的时候会触发,收集剩余图片
    handleRemove(file, fileList) {
      // console.log(file, fileList);
      this.spuImgList = fileList
    },
    // 收集添加图片
    handleAdd(response, file, fileList){
      this.spuImgList = fileList
      console.log(fileList)
    },
    // 图片预览功能
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 获取Spu表单信息
    async getSpuFormInfo(row) {
      // 获取SPU信息的数据
      let spuById = await this.$API.spu.reqgetSpuById(row.id);
      console.log("SpuById", spuById);
      if (spuById.code == 200) {
        this.spu = spuById.data;
      }
      //   获取品牌的信息
      let trademarkList = await this.$API.spu.reqgetTrademarkList();
      console.log("trademarkList", trademarkList);
      if (trademarkList.code == 200) {
        this.tmList = trademarkList.data;
      }
      //   获取spu图片的数据
      let spuImageList = await this.$API.spu.reqspuImageList(row.id);
      console.log("spuImageList", spuImageList);
      if (spuImageList.code == 200) {
        // 照片墙需要展示的数据【数组：数组里面的元素务必要有name、url属性】
        const imgList = spuImageList.data;
        imgList.forEach((item) => {
          item.name = item.imgName;
          item.url = item.imgUrl;
        });
        this.spuImgList = imgList;
      }
      //获取平台全部的销售属性
      let baseSaleAttrList = await this.$API.spu.reqbaseSaleAttrList();
      console.log("baseSaleAttrList", baseSaleAttrList);
      if (baseSaleAttrList.code == 200) {
        this.saleAttrList = baseSaleAttrList.data;
      }
    },
    // 添加销售属性
    addSaleAttrs(){
      // 已经收集需要添加的销售属性的信息,把收集到的销售属性数据进行分割
      const [baseSaleAttrId, saleAttrName] = this.attrIdAndAttrName.split(":")
      let newSaleAttrs = {
        baseSaleAttrId,
        saleAttrName,
        spuSaleAttrValueList: [],
      }
      //添加新的销售属性
      this.spu.spuSaleAttrList.push(newSaleAttrs)
      //清空数据
      this.attrIdAndAttrName = ''
    },
    // button显示为输入
    showInput(row) {
      // 挂载在销售属性身上的响应式数据inputVisible，控制button与input切换
      // row.inputVisible = true  //切换为inputVisible
      this.$set(row, "inputVisible", true)
      this.$set(row, "inputValue", '')
      console.log(row)
      // 点击聚焦
      this.$nextTick(_ => {
        this.$refs.saveTagInput.focus();
      });
    },
    // 属性值input失去焦点 -> button
    handleInputConfirm(row) {
      // 属性值的名称不能为空
      if (row.inputValue.trim() == "") {
        this.$message({
          message: "请输入正确的属性值",
          type: "warning",
        });
        return;
      }
      // 属性值的名称不能重复,如果重复不能失去焦点
      let isRepat = row.spuSaleAttrValueList.every(item => {
        return item.saleAttrValueName != row.inputValue
      })
      if(!isRepat) return
      //新增的销售属性值
      row.spuSaleAttrValueList.push({
        baseSaleAttrId: row.baseSaleAttrId,
        saleAttrValueName: row.inputValue
      })
      row.inputVisible = false
      // let inputValue = this.inputValue;
      // if (inputValue) {
      //   this.dynamicTags.push(inputValue);
      // }
      // this.inputVisible = false;
      // this.inputValue = '';
    },
    // 删除属性值
    handleClose(row, index) {
      row.spuSaleAttrValueList.splice(index, 1)
      // this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
    },
    // 保存spu表单(添加||修改)
    async saveOrUpdateSpuInfo(){
      // 整理收集的图片的信息
      this.spu.spuImageList = this.spuImgList.map((item) => {
        return{
          imgName: item.name,
          imgUrl: (item.response && item.response.data) || item.url
        }
      })
      //发请求
      let result = await this.$API.spu.reqSaveOrUpdateSpuInfo(this.spu);
      console.log("saveOrUpdateSpuInfo", result)
      if(result.code == 200){
        // 提示
        this.$message({
          type:"success",
          message: "保存成功"
        })
        //通知父组件回到场景0
        this.$emit("spuFormtoSpuInfo", {
          scene: 0,
          flag: this.spu.id ? 'updateSpu' : 'addSpu'
        })
      }
      // 清空数据
      // console.log('this._data', this._data)
      // console.log('this.$options.data()', this.$options.data())
      Object.assign(this._data, this.$options.data())
    },
    // 父组件点击添加SPU， 子组件发请求获取品牌和销售属性
    async addSpuData(category3id){
      this.spu.category3Id = category3id
      //   获取品牌的信息
      let trademarkList = await this.$API.spu.reqgetTrademarkList();
      console.log("addSpuData_trademarkList", trademarkList);
      if (trademarkList.code == 200) {
        this.tmList = trademarkList.data;
      }
      //获取平台全部的销售属性
      let baseSaleAttrList = await this.$API.spu.reqbaseSaleAttrList();
      console.log("addSpuData_baseSaleAttrList", baseSaleAttrList);
      if (baseSaleAttrList.code == 200) {
        this.saleAttrList = baseSaleAttrList.data;
      }
    },
    // 取消按钮
    cancle(){
      this.$emit('spuFormtoSpuInfo', {
        scene: 0,
        flag: ''
      })
      Object.assign(this._data, this.$options.data())
    },
  },
};
</script>

<style scoped>
</style>

<style>
  .el-tag + .el-tag {
    margin-left: 10px;
    margin-top: 5px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    margin-top: 5px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    margin-top: 5px;
    vertical-align: bottom;
  }
</style>